package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.exception.BuildingNotExistException;
import com.woniuxy.mapper.BuildingMapper;
import com.woniuxy.mapper.HouseMapper;
import com.woniuxy.model.Building;
import com.woniuxy.model.House;
import com.woniuxy.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Override
    public void insertHouse(House house) {
        //需要判断相关联的楼房是否存在
        Integer bid = house.getBuildingId();
        Building building = buildingMapper.selectById(bid);
        if(building==null){
            throw new BuildingNotExistException("不存在这样的楼房");
        }
        houseMapper.insert(house);
    }

    @Override
    public void deleteById(Integer id) {
        houseMapper.deleteById(id);
    }

    @Override
    public void updateById(House house) {
        if(house.getId()==null){
            throw new RuntimeException("错误的id参数");
        }
        //判断修改的信息中楼房id是否存在
        Integer bid = house.getBuildingId();
        Building building = buildingMapper.selectById(bid);
        if(building==null){
            throw new BuildingNotExistException("不存在这样的楼房");
        }
        houseMapper.updateById(house);
    }

    @Override
    public List<House> getAll(Integer page,Integer size) {
        QueryWrapper<House> queryWrapper = new QueryWrapper<>();
        Page<House> ipage = new Page<>(page,size);
        //先查询房间表
        List<House> houses = houseMapper.selectList(ipage,queryWrapper);
        //根据每一个房间的楼房号查询楼栋信息
        for(House house:houses){
            Building building = buildingMapper.selectById(house.getBuildingId());
            //set赋值
            house.setBuilding(building);
        }
        return houses;
    }

    @Override
    public House selectById(Integer id) {
        House house = houseMapper.selectById(id);
        if(house.getBuildingId()!=null){
            Building building = buildingMapper.selectById(house.getBuildingId());
            house.setBuilding(building);
        }else {
            throw new BuildingNotExistException("当前房间还未安排楼栋");
        }
        return house;
    }
}
